<?php

namespace ChannelThrift\Controller;

include 'WeaverAuctionTestCase.class.php';

use \Think\PhpUnit;
use \Thrift\Protocol\TBinaryProtocol;
use \Thrift\Protocol\TMultiplexedProtocol;
use \Thrift\Transport\THttpClient;
use \Thrift\Transport\TBufferedTransport;
use \Thrift\Exception\TException;

global $isClean;
$isClean = true;

/**
 * 拍卖单元测试;
    使用示例:
    phpunit --filter testCreateEditScene Tests/AuctionControllerTest.class.php
    phpunit --filter testCreateOrder Tests/AuctionControllerTest.class.php
    phpunit --filter testAuditOrder Tests/AuctionControllerTest.class.php
    phpunit --filter testStartTrigger Tests/AuctionControllerTest.class.php
    phpunit --filter testEndTrigger Tests/AuctionControllerTest.class.php

    phpunit --filter testBid Tests/AuctionControllerTest.class.php
    phpunit --filter testBidding Tests/AuctionControllerTest.class.php
    phpunit --filter testBiddingDeal Tests/AuctionControllerTest.class.php

 * @requires extension mysqli
 * @requires extension redis
 * @requires extension PHP 5.4.45
 */
class AuctionControllerTest extends WeaverAuctionTestCase
{

    private $client = null;
    private $redis = null;
    private $dealerID = 238;
    private $orderID = 2570;
    private $redisDatabase = 0;

    /**
    @before
     */
    public function testThriftClient()
    {
        $client = $this->getThriftClient('AuctionService','/Auction/run','liguohua.auction.weaver.s.isou365.cn','80');
        $this->client = $client;
        $this->redis = $this->getRedis();
    }

    /**
     * 创建及修改场
     */
    public function testCreateEditScene()
    {

        $inParams = new \Services\AuctionService\inParamsCreateEditScene();
        $starttime = date('Y-m-d H:i:00',strtotime('+5 minute'));
        $inParams->name = $starttime.'场';
        $inParams->starttime = strtotime($starttime);//必选(时间戳)
        $inParams->branchId = 33;//34
        $inParams->city = 110000;//330100
        $inParams->sceneActivity = 0;//可选
        $inParams->empId = 0;//可选
        $inParams->sceneId = 0;//可选（有值测试修改程序，无值测试添加程序）

        $result = $this->client->createEditScene($inParams);
        $this->assertTrue($result);

    }

    /**
     * 上拍
     */
    public function testCreateOrder()
    {

        $inParams = new \Services\AuctionService\inParamsCreateOrder();

        $inParams->carId            = 2260;     //报告ID 2260
        $inParams->sceneId          = 2719;     //场ID 2719
        $inParams->estElapsedTime   = 60*5;     //预计时长
        $inParams->bidStartPrice    = 100000;   //起拍价
        $inParams->transferFee      = 800;      //交付服务费
        $inParams->biddingStartTime = '';       //（可选,有值表示定时拍，否则是顺序单)竞拍开始时间
        $inParams->coupon           = 200;      //（可选）代金券
        $inParams->showReservePrice = true;     //（可选）是否显示保留价
        $inParams->empId            = 0;        //（可选）上拍人

        $result = $this->client->createOrder($inParams);
        $this->assertTrue($result);

    }

    /**
     * 上拍审核
     */
    public function testAuditOrder(){
        $orderId = 2628;
        $result = true;//true pass,false reject
        $remark = '';//
        $empId = 10;
        $result = $this->client->auditOrder($orderId,$result,$remark,$empId);
        $this->assertTrue($result);
    }

    /**
     * 钟点服务-开始竞拍
     */
    public function testStartTrigger(){
        $time = strtotime(date('Y-m-d H:i:00'));
        $time = strtotime('2017-06-09 18:00:00');
        $result = $this->client->startTrigger($time);
        $this->chkStartTriggerReturn($result);
    }


    public function testEndTrigger(){

            exit;
        $orderId = 2669;
        $isForce = true;
        $result = $this->client->endTrigger($orderId,$isForce);
        $this->chkStartTriggerReturn($result);
    }

    public function testBid(){
        $dealer_id  = 243;
        $order_id   = 2646;
        $price      = 19200;
        $dev_type   = 0;

        $result = $this->client->bid($dealer_id, $order_id, $price, $dev_type);
        $this->assertTrue($result);
    }

    public function testBidding(){
        $inParamsBidding = new \Services\AuctionService\inParamsBidding();
        $inParamsBidding->orderId     = 2646;
        $inParamsBidding->dealerId    = 243;   //车商ID
        $inParamsBidding->orgPrice    = 18900;   //基价
        $inParamsBidding->addPrice    = 300;   //加价
        $inParamsBidding->price       = 0;      //出价（自定义出价）
        $inParamsBidding->devType     = 1;           //出价设备类型
        $inParamsBidding->isAuto      = true;        //是否智能出价
        $inParamsBidding->biddingTime = $this->ms_time();     //出价时间(毫秒)

        $result = $this->client->bidding($inParamsBidding);
        $this->assertTrue($result);
    }

    public function testBiddingDeal(){
        $biddingMsg = new \Services\AuctionService\BiddingMsg();
        $biddingMsg->orderId     = 2646;
        $biddingMsg->dealerId    = 243;   //车商ID
        $biddingMsg->orgPrice    = 18900;   //基价
        $biddingMsg->addPrice    = 300;   //加价
        $biddingMsg->price       = 0;      //出价（自定义出价）
        $biddingMsg->devType     = 1;           //出价设备类型
        $biddingMsg->isAuto      = true;        //是否智能出价
        $biddingMsg->biddingTime = $this->ms_time();     //出价时间(毫秒)

        $result = $this->client->biddingDeal($biddingMsg);
        $this->assertTrue($result);
    }

    /**
    检查接口返回的格式
     */
    private function chkStartTriggerReturn(&$return){
        $this->assertTrue(is_array($return));
        //$this->assertInstanceOf('\Services\AuctionService\Auction',$return);
        if($return){
            foreach($return  as $val){
                $this->assertObjectHasAttribute('orderId',$val);
                $this->assertObjectHasAttribute('biddingStartTime',$val);
                $this->assertObjectHasAttribute('estElapsedTime',$val);
                $this->assertObjectHasAttribute('actElapsedTime',$val);
                $this->assertObjectHasAttribute('isTimingOrder',$val);
                $this->assertObjectHasAttribute('sceneId',$val);
                $this->assertObjectHasAttribute('sceneStartTime',$val);
            }
        }
    }

    /**
    @param serviceName 服务模块名
    @param servicePath 服务路径
    @param serviceDomain 服务域名
    @param servicePort 服务端口
    @return thriftclient
     */
    private function getThriftClient($serviceName,$servicePath,$serviceDomain,$servicePort=80)
    {
        if (!$serviceName){
            //抛出异常
            return false;
        }
        $handle = new THttpClient($serviceDomain, $servicePort, $servicePath);
        $transport = new TBufferedTransport($handle);
        $protocol = new TBinaryProtocol($transport);
        $auctionProtocol = new TMultiplexedProtocol($protocol, $serviceName);
        $serviceName='\\Services\\'.$serviceName.'\\'.$serviceName.'Client';
        $client = new $serviceName($auctionProtocol);
        return $client;
    }

    private function getRedis(){
        $config = require ROOT_PATH.'Application/ChannelThrift/Conf/redis.php';
        $redis = new \Redis();
        $redis->connect($config['REDIS_HOST'],$config['REDIS_PORT']);
        $redis->select($this->redisDatabase);
        return $redis;
    }


    /**
     * 计算当前时间毫秒
     * @return float
     */
    private function ms_time() {
        list($usec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0d',(floatval($usec)+floatval($sec))*1000);
    }


}
